import router from '@/router'
import store from './store'
import nprogress from 'nprogress'
import {asyncRoutes} from '@/router'
import 'nprogress/nprogress.css'

/**
 *前置守卫
 *
*/
const whiteList =['/login','/404']
router.beforeEach(async(to,from,next)=>{
  nprogress.start()
  if(store.getters.token){
    if(to.path=='/login'){
       next('/')
       nprogress.start()
    }else{
       // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          // return true/false
          return roles.menus.includes(item.name)
        }) // 筛选后的路由
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
        store.commit('user/setRoutes',filterRoutes)
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      } else {
        next() // 放过
      }
    }
  }else{
    if(whiteList.includes(to.path)){
      next()
    }else{
      next('/login')
      nprogress.start()
    }
  }
})
/** *
 * 后置守卫
 * **/
router.afterEach(() => {
  nprogress.done()
})